<?php

namespace App\Controllers\User;

use App\Controllers\FrontBase;
use App\Models\UserModel;

class Reg extends FrontBase
{

    protected $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    public function index()
    {
        if (IS_POST) {

            $data = $this->request->getPost('data');

            if (!$this->check_captcha('imgcode')) {
                $this->_json(1, '图片验证码不正确');
            }

            //短信验证码
            $randcode = $this->session->getTempdata('randcode');
            if (!isset($randcode) || !isset($data['smscode']) || $randcode != $data['smscode']) {
                $this->_json(1, '短信证码不正确');
            } else {
                unset($data['smscode']);
            }

            if (!isset($data['repassword']) || $data['repassword'] !== $data['password']) {
                $this->_json(1, '两次密码不一致');
            } else {
                unset($data['repassword']);
            }

            $rt = $this->userModel->register($data);
            $this->_json($rt['code'], $rt['msg']);

        }
        $vdata = [
            'meta_title' => '注册用户-首页',
        ];
        return view('user/reg.html', $vdata);
    }

    public function sendSms()
    {
        if (IS_POST) {
            //验证码
            if (!$this->checkRandCaptcha('randcode')) {
                $this->_json(1, '验证码不正确');
            }
            $randcode = $this->request->getPost('randcode');
            $phone = $this->request->getPost('phone');

            if (isset($phone) && isphone($phone)) {
                //发送短信
                $smsLib = new \App\Libraries\TencentSms();
                $code = mt_rand(100000, 999999) . '';
                $res = $smsLib->sendRegSms($phone, [$code]);
                if ($res['code'] == 0) {
                    $this->session->setTempdata('randcode', $code, 120);
                    $this->_json(0, $res['msg']);
                }
                $this->_json(1, $res['msg']);
            } else {
                $this->_json(1, '手机号码可能有误');
            }

        }
    }

}
